"""
初始化chrome驱动模块
chorome-driver下载地址: https://googlechromelabs.github.io/chrome-for-testing/#stable
"""

from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait

from .paths import WEBDRIVER_PATH


def init_browser(headless=False):
    option = ChromeOptions()
    if headless:
        option.add_argument("--headless")
    option.add_experimental_option('excludeSwitches', ['enable-logging'])
    # option.add_experimental_option('excludeSwitches', ['enable-automation'])
    option.add_argument(
        "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36")
    # option.add_experimental_option('excludeSwitches', ['enable-automation'])
    option.add_experimental_option('useAutomationExtension', False)
    service = Service(WEBDRIVER_PATH)
    browser: WebDriver = webdriver.Chrome(service=service, options=option)
    browser.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
        'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
    })
    browser.minimize_window()
    wait = WebDriverWait(browser, 30)

    return browser, wait


browser, wait = init_browser()
